# -*- coding: utf-8 -*-

# from django.http import HttpResponse
import json
from django.core import serializers

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render

from django.db.models import Q
from datetime import datetime

from AchievementsModel.models import User
from AchievementsModel.models import Score
from AchievementsModel.models import ScoreDate
from AchievementsModel.models import Advice

# 登录
def login(request):
    if request.method == 'GET':
        return render(request, 'home/login.html')
    else:
        # print(request.POST)
        if 'user_nick' in request.POST and 'user_pwd' in request.POST:
            if checkNickAndPwd(request, request.POST['user_nick'], request.POST['user_pwd']):
                return HttpResponseRedirect('/index')
        return render(request, 'home/login.html', { 'error': '用户名或密码错误'})

# 登出
def logout(request):
    if request.method == 'GET':
        if request.session.has_key('user'):
            del request.session['user']
        return HttpResponseRedirect('/login')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 首页
def index(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        return render(request, 'home/index.html', userData(request))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 个人绩效管理
def score(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        if request.GET.get('myself'):
            myself = request.GET.get('myself')
        else:
            myself = ""
        if request.GET.get('date'):
            date = request.GET.get('date')
        else:
            date = ""
        if request.GET.get('sort'):
            sort = request.GET.get('sort')
        else:
            sort = ""
        return render(request, 'home/score.html', scoreData(request, myself, date, sort))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 个人评分添加
def scoreAdd(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        return render(request, 'home/score_add.html', scoreAddData(request))
    else:
        print(request.POST)
        id = request.session['user']['pk']
        # 当前是否有评测
        if not request.POST['be_review_date'] or request.POST['be_review_date'] == "":
            return HttpResponseRedirect('/score_add')
        # 查询是否已填写评测，有则更新
        score = Score.objects.filter(Q(review_id=id) & Q(be_review_id=id) & Q(be_review_date=request.POST['be_review_date']))
        print(request.session['user'])
        if score:
            score.update(review_id=request.session['user']['pk'], be_review_id=request.session['user']['pk'], \
                         be_review_date=request.POST['be_review_date'], score_work=request.POST['score_work'], \
                         score_quality=request.POST['score_quality'], score_skill=request.POST['score_skill'], \
                         score_attitude=request.POST['score_attitude'])
        else:
            addscore = Score(review_id=request.session['user']['pk'], be_review_id=request.session['user']['pk'], \
                         be_review_date=request.POST['be_review_date'], score_work=request.POST['score_work'], \
                         score_quality=request.POST['score_quality'], score_skill=request.POST['score_skill'], \
                         score_attitude=request.POST['score_attitude'])
            addscore.save()
        return HttpResponseRedirect('/score')

# 同事绩效管理
def scores(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        if request.GET.get('buser'):
            buser = request.GET.get('buser')
        else:
            buser = ""
        if request.GET.get('date'):
            date = request.GET.get('date')
        else:
            date = ""
        if request.GET.get('sort'):
            sort = request.GET.get('sort')
        else:
            sort = ""
        return render(request, 'home/scores.html', scoresData(request, buser, date, sort))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 同事评分添加
def scoresAdd(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        return render(request, 'home/scores_add.html', scoresAddData(request))
    else:
        # 当前是否有评测
        if not request.POST['be_review_date'] or request.POST['be_review_date'] == "":
            return HttpResponseRedirect('/scores_add')
        # print(request.POST)
        id = request.session['user']['pk']
        # 遍历所有同事
        for item in scoresAddData(request)['user_data']:
            work = 'score_work' + str(item['pk'])
            quality = 'score_quality' + str(item['pk'])
            skill = 'score_skill' + str(item['pk'])
            attitude = 'score_attitude' + str(item['pk'])
            print(id, item['pk'], request.POST['be_review_date'], request.POST[work], request.POST[quality], request.POST[skill], request.POST[attitude])
            # 查询是否已填写评测，有则更新
            score = Score.objects.filter(Q(review_id=id) & Q(be_review_id=item['pk']) & Q(be_review_date=request.POST['be_review_date']))
            if score:
                score.update(score_work=request.POST[work], score_quality=request.POST[quality], \
                             score_skill=request.POST[skill], score_attitude=request.POST[attitude])
            else:
                addscore = Score(review_id=id, be_review_id=item['pk'], be_review_date=request.POST['be_review_date'], \
                             score_work=request.POST[work], score_quality=request.POST[quality], \
                             score_skill=request.POST[skill], score_attitude=request.POST[attitude])
                addscore.save()
        return HttpResponseRedirect('/scores')

# 帮助反馈
def help(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/login')
    if request.method == 'GET':
        return render(request, 'home/help.html', defaultData(request))
    else:
        id = request.session['user']['pk']
        adddesc = Advice(user_id=id, descript=request.POST['descript'])
        adddesc.save()
        return HttpResponseRedirect('/index')

# 验证用户名密码
def checkNickAndPwd(request, nick, pwd):
    result = User.objects.filter(Q(user_nick=nick) & Q(user_pwd=pwd))
    if result:
        data = serializers.serialize("json", result)
        request.session['user'] = json.loads(data)[0]
        return True
    return False

# 查询个人信息

# 获取用户表数据
def userData(request):
    result = User.objects.all()
    data = serializers.serialize("json", result)
    context = {
        'user': request.session['user'],
        'data': json.loads(data)
    }
    # print(context)
    return context

# 自我评测页面数据
def scoreData(request, myself, date, sort):
    id = request.session['user']['pk']
    result = Score.objects.filter(Q(be_review_id=id))
    if myself == "on":
        result = result.filter(Q(review_id=id))
    if date != "":
        result = result.filter(Q(be_review_date=date))
    if sort == "0":
        # result = result.order_by("score_work")
        result = result.extra(select={'score_totol': 'score_work + score_quality + score_skill + score_attitude'}).order_by('score_totol')
        # extra(select={'tag_name': 'name'})
    if sort == "1":
        # result = result.order_by("-score_work")
        result = result.extra(select={'score_totol': 'score_work + score_quality + score_skill + score_attitude'}).order_by('-score_totol')
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)

    # 姓名数组
    userArr = User.objects.all()
    userArrStr = serializers.serialize("json", userArr)
    userArrJson = json.loads(userArrStr)
    # 选择日期数组
    # dateArr = Score.objects.values('be_review_date').distinct().order_by('-be_review_date')
    # print('>>>>>>>>>', dateArr)
    dateArr = ScoreDate.objects.all()
    dateArrStr = serializers.serialize("json", dateArr)
    dateArrJson = json.loads(dateArrStr)
    # 查询是否已测评
    dateStatus = ScoreDate.objects.filter(Q(status=True))
    dataStatusStr = serializers.serialize("json", dateStatus)
    dataStatusJson = json.loads(dataStatusStr)
    if dateStatus:
        status = True
        if Score.objects.filter(Q(review_id=id) & Q(be_review_id=id) & Q(be_review_date=dataStatusJson[0]['fields']['score_date'])):
            status = False
        context = {
            'user': request.session['user'],
            'data': dataJson,
            'date': date,
            'dateArr': dateArrJson,
            'userArr': userArrJson,
            'sort': sort,
            'myself': myself,

            'status': status,
            'status_date': dataStatusJson[0]
        }
    else:
        context = {
            'user': request.session['user'],
            'data': dataJson,
            'date': date,
            'dateArr': dateArrJson,
            'userArr': userArrJson,
            'sort': sort,
            'myself': myself,
        }
    # print(context)
    return context

# 添加自我评分页面数据
def scoreAddData(request):
    # 查询当前是否有评测
    dateStatus = ScoreDate.objects.filter(Q(status=True))
    dataStatusStr = serializers.serialize("json", dateStatus)
    dataStatusJson = json.loads(dataStatusStr)
    if dataStatusJson:
        # 查询是否填写过评测
        id = request.session['user']['pk']
        result = Score.objects.filter(Q(review_id=id) & Q(be_review_id=id) & Q(be_review_date=dataStatusJson[0]['fields']['score_date']))
        dataStr = serializers.serialize("json", result)
        dataJson = json.loads(dataStr)
        if dataJson:
            context = {
                'user': request.session['user'],
                'check_date': dataStatusJson[0],
                'data': dataJson[0]
            }
        else:
            context = {
                'user': request.session['user'],
                'check_date': dataStatusJson[0],
            }
    else:
        context = {
            'user': request.session['user'],
        }
    return context

# 同事评分数据
def scoresData(request, buser, date, sort):
    id = request.session['user']['pk']
    # 有date查询该日期的记录，没有则查询所有记录
    result = Score.objects.filter(Q(review_id=id) & ~Q(be_review_id=id))
    if buser != "":
        result = result.filter(Q(be_review_id=buser))
    if date != '':
        result = result.filter(Q(be_review_date=date))
    if sort == "0":
        # result = result.order_by("score_work")
        result = result.extra(select={'score_totol': 'score_work + score_quality + score_skill + score_attitude'}).order_by('score_totol')
        # extra(select={'tag_name': 'name'})
    if sort == "1":
        # result = result.order_by("-score_work")
        result = result.extra(select={'score_totol': 'score_work + score_quality + score_skill + score_attitude'}).order_by('-score_totol')
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)
    # 获取用户名
    for item in dataJson:
        user = User.objects.filter(id=item['fields']['be_review_id'])
        if user:
            userStr = serializers.serialize("json", user)
            userJson = json.loads(userStr)
            item['fields']['be_review_name'] = userJson[0]['fields']['user_name']
        else:
            item['fields']['be_review_name'] = item['fields']['be_review_id']

    # 转换类型
    try:
        buser = int(buser)
    except:
        buser = ""
    # 姓名数组
    userArr = User.objects.all()
    userArrStr = serializers.serialize("json", userArr)
    userArrJson = json.loads(userArrStr)
    # 选择日期数组
    # dateArr = Score.objects.values('be_review_date').distinct().order_by('-be_review_date')
    dateArr = ScoreDate.objects.all()
    dateArrStr = serializers.serialize("json", dateArr)
    dateArrJson = json.loads(dateArrStr)
    # 查询是否已测评
    dateStatus = ScoreDate.objects.filter(Q(status=True))
    dataStatusStr = serializers.serialize("json", dateStatus)
    dataStatusJson = json.loads(dataStatusStr)
    if dateStatus:
        status = True
        if Score.objects.filter(Q(review_id=id) & ~Q(be_review_id=id) & Q(be_review_date=dataStatusJson[0]['fields']['score_date'])):
            status = False
        context = {
            'user': request.session['user'],
            'data': dataJson,
            'date': date,
            'dateArr': dateArrJson,
            'userArr': userArrJson,
            'buser': buser,
            'sort': sort,

            'status': status,
            'status_date': dataStatusJson[0]
        }
    else:
        context = {
            'user': request.session['user'],
            'data': dataJson,
            'date': date,
            'dateArr': dateArrJson,
            'userArr': userArrJson,
            'buser': buser,
            'sort': sort,
        }
    # print(context)
    return context

# 添加同事评分页面数据
def scoresAddData(request):
    # 除自己外且position=0的用户
    id = request.session['user']['pk']
    result = User.objects.filter(~Q(id=id) & Q(position=0))
    dataUser = serializers.serialize("json", result)
    # 从ScoreDate中获取当前是否有测评
    dateStatus = ScoreDate.objects.filter(Q(status=True))
    dateStatusStr = serializers.serialize("json", dateStatus)
    dateStatusJson = json.loads(dateStatusStr)
    if dateStatusJson:
        # 查看是否有当前时间的评分信息
        id = request.session['user']['pk']
        result = Score.objects.filter(Q(review_id=id) & ~Q(be_review_id=id) & Q(be_review_date=dateStatusJson[0]['fields']['score_date']))
        dataStr = serializers.serialize("json", result)
        dataJson = json.loads(dataStr)
        if dataJson:
            context = {
                'user': request.session['user'],
                'check_date': dateStatusJson[0],
                'data': dataJson[0],
                'user_data': json.loads(dataUser)
            }
        else:
            context = {
                'user': request.session['user'],
                'check_date': dateStatusJson[0],
                'user_data': json.loads(dataUser)
            }
    else:
        context = {
            'user': request.session['user'],
            'user_data': json.loads(dataUser)
        }
    # print(context)
    return context

def defaultData(request):
    context = {
        'user': request.session['user'],
    }
    return context


